﻿using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.BLL;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Reflection;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using System.Data;
using IPR_StudyMeetingMrgSys.ViewModel;
using Newtonsoft.Json;
using System.Text;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    public class ExamController : ApiController
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        BLL.Exam bll = new BLL.Exam();
        /// <summary>
        /// 开始考试，保存考试信息
        /// </summary>
        /// <param name="exam"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Exam/CreateExamInfo")]
        public IHttpActionResult CreateExamInfo(int EPID)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                //每张试卷每个用户只允许考试一次，因此在此判断是否已经考试过，如已考试过，提示用户；如未考试过，加载新的考试；如有未完成的考试，返回未完成考试的考试ID，即EUID
                DataSet dataSet = bll.GetExamInfo(EPID, LoginUser.EmpID);
                if (dataSet.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToInt32(dataSet.Tables[0].Rows[0]["EUComplete"]) == 0)
                    {
                        if (Convert.ToInt32(dataSet.Tables[0].Rows[0]["RemainSeconds"]) <= 0)
                        {
                            bll.CloseExam(Convert.ToInt32(dataSet.Tables[0].Rows[0]["EUID"]), Convert.ToDateTime(dataSet.Tables[0].Rows[0]["EUStart"]).AddMinutes(Convert.ToInt32(dataSet.Tables[0].Rows[0]["EPExamDuration"])));
                            resultMsg.Info = "已进行过本场考试，因超时考试自动结束";
                        }
                        else
                        {
                            resultMsg.Data = dataSet.Tables[0].Rows[0]["EUID"];
                            resultMsg.Info = "在考试时间内，可继续进行考试";
                            resultMsg.Count = 1;
                        }
                    }
                    else
                    {
                        resultMsg.Info = "已进行过本场考试";
                    }
                }
                else//未获取到当前用户该场考试信息，则新建考试信息
                {
                    int EUID = bll.CreateExamInfo(EPID, LoginUser.UserInfo.UserID, LoginUser.UserInfo.UserName);
                    resultMsg.Info = EUID > 0 ? "生成试卷成功" : "生成试卷失败";
                    resultMsg.Data = EUID;
                    resultMsg.Count = EUID > 0 ? 1 : 0;
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 获取在线考试试卷信息（包括试卷信息和试卷答题信息）,如果考试已超时，则自动关闭
        /// </summary>
        /// <param name="EPID">试卷ID</param>
        /// <param name="EUID">考试ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Exam/GetExamInfo")]
        public IHttpActionResult GetExamInfo(int EPID, int EUID)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                DataSet dataSet = bll.GetExamInfo(EPID, LoginUser.EmpID, EUID);
                if (dataSet.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToInt32(dataSet.Tables[0].Rows[0]["RemainSeconds"]) <= 0)
                    {
                        bll.CloseExam(EUID, Convert.ToDateTime(dataSet.Tables[0].Rows[0]["EUStart"]).AddMinutes(Convert.ToInt32(dataSet.Tables[0].Rows[0]["EPExamDuration"])));
                        resultMsg.Info = "已进行过本场考试，因超时考试自动结束";
                    }
                    else
                    {
                        resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                        resultMsg.Data = dataSet.Tables;
                        resultMsg.Count = 1;
                    }
                }
                else
                {
                    resultMsg.Info = "未获取到相应数据";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 获取未完成考试信息，如有已超时未完成的考试，则自动关闭不返回数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Exam/GetNoComplatedExam")]
        public IHttpActionResult GetNoComplatedExam()
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                DataSet ds = bll.GetNoComplatedExam(LoginUser.UserInfo.UserID);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = ds.Tables[0];
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "未获取到相应数据";
                    resultMsg.Count = 0;
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 用户确认关闭考试
        /// </summary>
        /// <param name="EUID">考试编号</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Exam/CloseExam")]
        public IHttpActionResult CloseExam(int EUID)
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                bll.CloseExam(EUID, DateTime.Now);
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "关闭考试成功";
                resultMsg.Count = 1;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        #region 交卷操作
        /// <summary>
        /// 正常交卷
        /// </summary>
        /// <param name="list">答题详情</param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Exam/SubmitExam")]
        public IHttpActionResult SubmitExam(List<VM_SubmitExam> list)
        {
            return SubmitExam(list, false);
        }
        /// <summary>
        /// 异常交卷
        /// </summary>
        /// <param name="list">答题详情</param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Exam/SubmitExceptionExam")]
        public IHttpActionResult SubmitExceptionExam(List<VM_SubmitExam> list)
        {
            return SubmitExam(list, true);
        }

        #region 私有方法
        /// <summary>
        /// 交卷操作
        /// </summary>
        /// <param name="list">答题详情</param>
        /// <param name="isExceptionExam">是否异常交卷</param>
        /// <returns></returns>
        private IHttpActionResult SubmitExam(List<VM_SubmitExam> list,bool isExceptionExam)
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                Model.ExamUser examUser = new Model.ExamUser()
                {
                    EUID = list[0].EUID,
                    EUMark = 0,
                    EUEnd = DateTime.Now,
                    EUComplete = isExceptionExam ? 0 : 1
                };

                List<Model.ExamAnswer> examAnswers = new List<Model.ExamAnswer>();
                foreach (var item in list)
                {
                    examAnswers.Add(new Model.ExamAnswer()
                    {
                        EUID = item.EUID,
                        EQID = item.EQID,
                        EARAnswer = item.EARAnswer,
                        EAMark = 0
                    });
                }
                new BLL.Exam().SubmitExam(examUser, examAnswers, LoginUser.UserInfo);
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "交卷成功";
                resultMsg.Count = 1;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        #endregion
        #endregion
    }
}
